package pfq.demo.view;

import android.content.Context;
import android.graphics.Canvas;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.widget.RelativeLayout;

/**
 * TODO: document your custom view class.
 */
public class BViewGroup extends RelativeLayout {

    public BViewGroup(Context context) {
        super(context);
        init(null, 0);
    }

    public BViewGroup(Context context, AttributeSet attrs) {
        super(context, attrs);
        init(attrs, 0);
    }

    public BViewGroup(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        init(attrs, defStyle);
    }

    private void init(AttributeSet attrs, int defStyle) {

    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        Log.d("ViewRefresh", "BViewGroup-onMeasure()");
    }

    @Override
    protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
        super.onLayout(changed, left, top, right, bottom);
        Log.d("ViewRefresh", "BViewGroup-onLayout()");
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        Log.d("ViewRefresh", "BViewGroup-onDraw()");
    }

    @Override
    public boolean onInterceptTouchEvent(MotionEvent ev) {

        // 当触摸点到达自身顶部的时候，进行事件的拦截，这样MotionEvent会传递到自己的onTouchEvent()方法中
        if (ev.getY() <= 0) {
            return true;
        }

        return super.onInterceptTouchEvent(ev);
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {

        // down事件得返回true，否则move事件不会传递进来
        if (event.getAction() == MotionEvent.ACTION_DOWN) {
            return true;
        }

        if (event.getAction() == MotionEvent.ACTION_MOVE) {

            int[] location = new int[2];
            ((View) getParent()).getLocationOnScreen(location);

            setY(event.getRawY() - location[1]);
        }

        return super.onTouchEvent(event);
    }
}
